<template>
  <div class="template-detail" v-loading="loading">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <el-button @click="goBack" :icon="ArrowLeft" circle />
          <div>
            <h1>{{ template?.title || '模板详情' }}</h1>
            <p>查看和编辑试卷模板详细信息</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="editTemplate">
            <el-icon><Edit /></el-icon>
            编辑模板
          </el-button>
          <el-button type="success" @click="generatePaper">
            <el-icon><Document /></el-icon>
            生成试卷
          </el-button>
          <el-dropdown @command="handleCommand">
            <el-button>
              更多操作<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="copy">复制模板</el-dropdown-item>
                <el-dropdown-item command="export">导出模板</el-dropdown-item>
                <el-dropdown-item command="preview">预览试卷</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除模板</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div class="content-container">
      <el-row :gutter="24">
        <!-- 左侧主要内容 -->
        <el-col :span="16">
          <!-- 基本信息 -->
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
                <el-tag :type="getTypeColor(template?.paper_type)">
                  {{ getTypeLabel(template?.paper_type) }}
                </el-tag>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="模板名称">
                {{ template?.title }}
              </el-descriptions-item>
              <el-descriptions-item label="试卷类型">
                <el-tag :type="getTypeColor(template?.paper_type)">
                  {{ getTypeLabel(template?.paper_type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="总分">
                {{ template?.total_score }} 分
              </el-descriptions-item>
              <el-descriptions-item label="考试时长">
                {{ template?.duration }} 分钟
              </el-descriptions-item>
              <el-descriptions-item label="题目总数">
                {{ template?.total_questions }} 题
              </el-descriptions-item>
              <el-descriptions-item label="组卷方式">
                <el-tag>
                  {{ getMethodLabel(template?.generation_method) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="及格分数">
                {{ template?.passing_score }} 分
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="template?.is_active ? 'success' : 'danger'">
                  {{ template?.is_active ? '启用' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">
                {{ formatDate(template?.created_at) }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间" :span="2">
                {{ formatDate(template?.updated_at) }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="template-description" v-if="template?.description">
              <h4>描述</h4>
              <p>{{ template.description }}</p>
            </div>
          </el-card>

          <!-- 试卷结构 -->
          <el-card class="structure-card">
            <template #header>
              <div class="card-header">
                <span>试卷结构</span>
                <el-button size="small" @click="editStructure">
                  <el-icon><Edit /></el-icon>
                  编辑结构
                </el-button>
              </div>
            </template>

            <div class="sections-container">
              <div
                v-for="(section, index) in template?.sections || []"
                :key="section.id"
                class="section-item"
              >
                <div class="section-header">
                  <div class="section-info">
                    <h3>{{ section.title }}</h3>
                    <el-tag size="small">{{ section.question_type }}</el-tag>
                  </div>
                  <div class="section-stats">
                    <span>{{ section.question_count }} 题</span>
                    <span>{{ section.total_score }} 分</span>
                  </div>
                </div>

                <div class="section-content">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <div class="stat-item">
                        <span class="label">每题分值：</span>
                        <span class="value">{{ section.score_per_question }} 分</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="stat-item">
                        <span class="label">题目数量：</span>
                        <span class="value">{{ section.question_count }} 题</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="stat-item">
                        <span class="label">总分值：</span>
                        <span class="value">{{ section.total_score }} 分</span>
                      </div>
                    </el-col>
                  </el-row>

                  <div class="difficulty-distribution" v-if="section.difficulty_distribution">
                    <h4>难度分布</h4>
                    <div class="difficulty-chart">
                      <div
                        v-for="(count, difficulty) in section.difficulty_distribution"
                        :key="difficulty"
                        class="difficulty-item"
                      >
                        <span class="difficulty-label">{{ getDifficultyLabel(difficulty) }}</span>
                        <div class="difficulty-bar">
                          <div
                            class="difficulty-fill"
                            :class="difficulty"
                            :style="{ width: getDifficultyPercent(section, difficulty) }"
                          ></div>
                        </div>
                        <span class="difficulty-count">{{ count }} 题</span>
                      </div>
                    </div>
                  </div>

                  <div class="section-description" v-if="section.description">
                    <p>{{ section.description }}</p>
                  </div>
                </div>

                <div class="section-actions">
                  <el-button size="small" @click="editSection(section)">
                    编辑部分
                  </el-button>
                  <el-button size="small" @click="previewQuestions(section)">
                    预览题目
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 配置参数 -->
          <el-card class="config-card">
            <template #header>
              <span>配置参数</span>
            </template>

            <el-row :gutter="20">
              <el-col :span="12">
                <div class="config-item">
                  <h4>随机设置</h4>
                  <el-descriptions :column="1" size="small">
                    <el-descriptions-item label="题目顺序">
                      {{ template?.config?.random_order ? '随机' : '固定' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="选项顺序">
                      {{ template?.config?.random_options ? '随机' : '固定' }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="config-item">
                  <h4>显示设置</h4>
                  <el-descriptions :column="1" size="small">
                    <el-descriptions-item label="显示总分">
                      {{ template?.config?.show_total_score ? '显示' : '隐藏' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="显示计时">
                      {{ template?.config?.show_timer ? '显示' : '隐藏' }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>

        <!-- 右侧统计信息 -->
        <el-col :span="8">
          <!-- 使用统计 -->
          <el-card class="stats-card">
            <template #header>
              <span>使用统计</span>
            </template>

            <div class="stats-grid">
              <div class="stat-box">
                <div class="stat-value">{{ template?.usage_count || 0 }}</div>
                <div class="stat-label">使用次数</div>
              </div>
              <div class="stat-box">
                <div class="stat-value">{{ template?.generated_papers || 0 }}</div>
                <div class="stat-label">生成试卷</div>
              </div>
              <div class="stat-box">
                <div class="stat-value">{{ template?.avg_score || 0 }}</div>
                <div class="stat-label">平均分</div>
              </div>
              <div class="stat-box">
                <div class="stat-value">{{ template?.pass_rate || 0 }}%</div>
                <div class="stat-label">及格率</div>
              </div>
            </div>
          </el-card>

          <!-- 难度分析 -->
          <el-card class="difficulty-card">
            <template #header>
              <span>难度分析</span>
            </template>

            <div class="difficulty-analysis">
              <div class="overall-difficulty">
                <div class="difficulty-label">整体难度</div>
                <div class="difficulty-level">
                  <el-rate
                    v-model="overallDifficulty"
                    disabled
                    show-score
                    text-color="#ff9900"
                  />
                </div>
              </div>

              <div class="difficulty-chart">
                <div
                  v-for="(count, difficulty) in template?.difficulty_distribution || {}"
                  :key="difficulty"
                  class="difficulty-stat"
                >
                  <div class="stat-label">{{ getDifficultyLabel(difficulty) }}</div>
                  <div class="stat-bar">
                    <div
                      class="stat-fill"
                      :class="difficulty"
                      :style="{ width: getOverallDifficultyPercent(difficulty) }"
                    ></div>
                  </div>
                  <div class="stat-count">{{ count }} 题</div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 历史记录 -->
          <el-card class="history-card">
            <template #header>
              <div class="card-header">
                <span>生成记录</span>
                <el-button size="small" text @click="viewAllHistory">
                  查看全部
                </el-button>
              </div>
            </template>

            <div class="history-list">
              <div
                v-for="record in recentHistory"
                :key="record.id"
                class="history-item"
                @click="viewPaper(record)"
              >
                <div class="history-info">
                  <div class="history-title">{{ record.title }}</div>
                  <div class="history-meta">
                    {{ formatDate(record.created_at) }} · {{ record.creator }}
                  </div>
                </div>
                <el-icon class="history-arrow"><ArrowRight /></el-icon>
              </div>
            </div>

            <div v-if="recentHistory.length === 0" class="empty-history">
              <el-empty description="暂无生成记录" :image-size="80" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 生成试卷对话框 -->
    <GeneratePaperDialog
      v-model="showGenerateDialog"
      :template="template"
      @success="handleGenerateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Edit, Document, ArrowDown, ArrowRight
} from '@element-plus/icons-vue'
import { examPaperApi } from '@/api/examPaper'
import GeneratePaperDialog from './components/GeneratePaperDialog.vue'
import { format } from 'date-fns'

const router = useRouter()
const route = useRoute()

// 响应式数据
const template = ref(null)
const loading = ref(false)
const showGenerateDialog = ref(false)
const recentHistory = ref([])

// 计算属性
const overallDifficulty = computed(() => {
  const distribution = template.value?.difficulty_distribution || {}
  const total = Object.values(distribution).reduce((sum: number, count: number) => sum + count, 0)
  if (total === 0) return 0

  const weightedSum =
    (distribution.easy || 0) * 1 +
    (distribution.medium || 0) * 2 +
    (distribution.hard || 0) * 3

  return Math.round(weightedSum / total)
})

// 方法
const loadTemplate = async () => {
  try {
    loading.value = true
    const templateId = route.params.id
    const response = await examPaperApi.getTemplate(templateId)
    template.value = response.data

    // 加载生成记录
    await loadHistory()
  } catch (error) {
    console.error('Failed to load template:', error)
    ElMessage.error('加载模板详情失败')
    router.push('/exam-paper/templates')
  } finally {
    loading.value = false
  }
}

const loadHistory = async () => {
  try {
    const response = await examPaperApi.getPapers({
      template: route.params.id,
      page_size: 5,
      ordering: '-created_at'
    })
    recentHistory.value = response.data.results || []
  } catch (error) {
    console.error('Failed to load history:', error)
  }
}

const goBack = () => {
  router.push('/exam-paper/templates')
}

const editTemplate = () => {
  router.push(`/exam-paper/templates/${route.params.id}/edit`)
}

const editStructure = () => {
  router.push(`/exam-paper/templates/${route.params.id}/structure`)
}

const generatePaper = () => {
  showGenerateDialog.value = true
}

const editSection = (section: any) => {
  router.push(`/exam-paper/templates/${route.params.id}/sections/${section.id}/edit`)
}

const previewQuestions = (section: any) => {
  router.push(`/exam-paper/templates/${route.params.id}/sections/${section.id}/preview`)
}

const handleCommand = async (command: string) => {
  switch (command) {
    case 'copy':
      await copyTemplate()
      break
    case 'export':
      await exportTemplate()
      break
    case 'preview':
      previewPaper()
      break
    case 'delete':
      await deleteTemplate()
      break
  }
}

const copyTemplate = async () => {
  try {
    const response = await examPaperApi.copyTemplate(route.params.id)
    ElMessage.success('模板复制成功')
    router.push(`/exam-paper/templates/${response.data.id}`)
  } catch (error) {
    console.error('Failed to copy template:', error)
    ElMessage.error('模板复制失败')
  }
}

const exportTemplate = async () => {
  try {
    const response = await examPaperApi.exportTemplate(route.params.id)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${template.value.title}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('模板导出成功')
  } catch (error) {
    console.error('Failed to export template:', error)
    ElMessage.error('模板导出失败')
  }
}

const previewPaper = () => {
  // 生成预览试卷
  router.push(`/exam-paper/templates/${route.params.id}/preview`)
}

const deleteTemplate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板"${template.value.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await examPaperApi.deleteTemplate(route.params.id)
    ElMessage.success('模板删除成功')
    router.push('/exam-paper/templates')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete template:', error)
      ElMessage.error('模板删除失败')
    }
  }
}

const viewPaper = (record: any) => {
  router.push(`/exam-paper/papers/${record.id}`)
}

const viewAllHistory = () => {
  router.push(`/exam-paper/papers?template=${route.params.id}`)
}

const handleGenerateSuccess = () => {
  showGenerateDialog.value = false
  ElMessage.success('试卷生成成功')
  loadHistory() // 重新加载历史记录
}

// 辅助方法
const getTypeColor = (type: string) => {
  const colors = {
    formal: 'primary',
    mock: 'success',
    practice: 'warning',
    competition: 'danger'
  }
  return colors[type] || 'info'
}

const getTypeLabel = (type: string) => {
  const labels = {
    formal: '正式考试',
    mock: '模拟考试',
    practice: '练习试卷',
    competition: '竞赛试卷'
  }
  return labels[type] || type
}

const getMethodLabel = (method: string) => {
  const labels = {
    random: '随机组卷',
    intelligent: '智能组卷',
    manual: '手工组卷'
  }
  return labels[method] || method
}

const getDifficultyLabel = (difficulty: string) => {
  const labels = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labels[difficulty] || difficulty
}

const getDifficultyPercent = (section: any, difficulty: string) => {
  const distribution = section.difficulty_distribution || {}
  const total = Object.values(distribution).reduce((sum: number, count: number) => sum + count, 0)
  if (total === 0) return '0%'
  const percent = ((distribution[difficulty] || 0) / total * 100).toFixed(1)
  return `${percent}%`
}

const getOverallDifficultyPercent = (difficulty: string) => {
  const distribution = template.value?.difficulty_distribution || {}
  const total = Object.values(distribution).reduce((sum: number, count: number) => sum + count, 0)
  if (total === 0) return '0%'
  const percent = ((distribution[difficulty] || 0) / total * 100).toFixed(1)
  return `${percent}%`
}

const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm')
}

// 生命周期
onMounted(() => {
  loadTemplate()
})
</script>

<style scoped>
.template-detail {
  padding: 24px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-section h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: var(--el-text-color-primary);
}

.title-section p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content-container {
  margin-bottom: 24px;
}

.info-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-description {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.template-description h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.template-description p {
  margin: 0;
  color: var(--el-text-color-regular);
  line-height: 1.6;
}

.structure-card {
  margin-bottom: 24px;
}

.sections-container {
  space-y: 20px;
}

.section-item {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: var(--el-bg-color);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-info h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.section-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.section-content {
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.stat-item .label {
  color: var(--el-text-color-regular);
}

.stat-item .value {
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.difficulty-distribution {
  margin-top: 16px;
}

.difficulty-distribution h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.difficulty-chart {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.difficulty-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.difficulty-label {
  width: 40px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.difficulty-bar {
  flex: 1;
  height: 6px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 3px;
  overflow: hidden;
}

.difficulty-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.difficulty-fill.easy {
  background-color: #67C23A;
}

.difficulty-fill.medium {
  background-color: #E6A23C;
}

.difficulty-fill.hard {
  background-color: #F56C6C;
}

.difficulty-count {
  width: 40px;
  text-align: right;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.section-description {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.section-description p {
  margin: 0;
  font-size: 13px;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.config-card {
  margin-bottom: 24px;
}

.config-item {
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.config-item h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.stats-card {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.stat-box {
  text-align: center;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.difficulty-card {
  margin-bottom: 24px;
}

.difficulty-analysis {
  space-y: 20px;
}

.overall-difficulty {
  margin-bottom: 20px;
}

.difficulty-label {
  font-size: 14px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.difficulty-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.difficulty-stat {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-label {
  width: 40px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.stat-bar {
  flex: 1;
  height: 8px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  overflow: hidden;
}

.stat-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.stat-fill.easy {
  background-color: #67C23A;
}

.stat-fill.medium {
  background-color: #E6A23C;
}

.stat-fill.hard {
  background-color: #F56C6C;
}

.stat-count {
  width: 40px;
  text-align: right;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.history-card {
  margin-bottom: 24px;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.history-item:hover {
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  padding-left: 8px;
  padding-right: 8px;
}

.history-item:last-child {
  border-bottom: none;
}

.history-title {
  font-size: 14px;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.history-meta {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.history-arrow {
  color: var(--el-text-color-placeholder);
}

.empty-history {
  text-align: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-container .el-col:first-child {
    span: 24;
  }

  .content-container .el-col:last-child {
    span: 24;
  }
}

@media (max-width: 768px) {
  .template-detail {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>